<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/25
 * Time: 10:44
 */

namespace app\index\server;


use app\index\model\Category as CategoryModel;
use app\index\model\Product as ProductModel;
use app\lib\exception\DatabaseException;
use think\Exception;

class ProductServer extends BaseServer
{
    public function getList($params = [])
    {
        $params = $this->prep_param($params);
        try {
            // 总条数
            $count = ProductModel::count();
            $list = ProductModel::with(['img', 'category'])
                ->order($params['sort'], $params['order'])
                ->limit($params['offset'], $params['limit'])
                ->select();
        } catch (Exception $e) {
            // 有些问题 应该抛出错误异常
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function addOrUpdate($params = [])
    {
        // 商品名的处理
        $primary = isset($params['primary_key']) ? $params['primary_key'] : '';
        $product_name = $this->check_product_name($params['name'], $primary);
        if($product_name) {
            return setMsg(0, '输入的商品名称重复');
        }
        $category = $this->check_category($params['category']);
        if(!$category) {
            return setMsg(0, '输入的分类名不存在');
        }
        // 处理上传图片
        $img_result = $this->handle_image($params['alias'], $params['url'], 'product', $primary);
        if($img_result['status'] == 0) {
            return setMsg(0, $img_result['msg']);
        }
        $prep_data = [
            'name' => $params['name'],
            'summary' => $params['summary'],
            'member_price' => $params['member_price'],
            'price' => $params['price'],
            'category_id' => $category->id,
            'img_id' => $img_result['img_id'],
            'status' => $params['status'],
            'cp_hot' => $params['cp_hot'],
            'url' => $img_result['msg']
        ];
        try {
            if($primary) {
                // 更新
                $result = ProductModel::where('id', $primary)
                    ->update($prep_data);
            } else {
                // 新增
                $result = ProductModel::insert($prep_data);
            }
            if(!$result) {
                return setMsg(0, '商品操作失败');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '商品操作成功');
    }


    public function changeStatus($id)
    {
        try {
            $info = ProductModel::where('id', $id)
                ->find();
            $info->status = abs(($info->status) - 1);
            $result = $info->save();
            if(!$result) {
                return setMsg(0, '修改此商品状态失败');
            }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改此商品 状态成功');
    }

    public function detail($id)
    {
        try {
            $info = ProductModel::with(['img', 'category'])
                ->where('id', '=', $id)
                ->find();
            if(!$info) {
                return setMsg(0, '未找到此商品的信息');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, 'OK', $info);
    }

    protected function check_product_name($name, $primary)
    {
        $result = ProductModel::where('name', '=', $name)
            ->where('id', '<>', $primary)
            ->find();
        if($result) {
            return $result;
        }
        return false;
    }

    protected function check_category($name)
    {
        $result = CategoryModel::where('name', '=', $name)
            ->find();
        if(!$result) {
            return false;
        }
        return $result;
    }
}